<template>
  <div class="favorites-container">
    <!-- 顶部导航栏 -->
    <van-nav-bar
      title="我的收藏"
      left-arrow
      @click-left="$router.back()"
      fixed
    />

    <div class="content">
      <van-empty v-if="loading" description="加载中...">
        <template #image>
          <van-loading type="spinner" size="36" />
        </template>
      </van-empty>

      <van-empty
        v-else-if="collections.length === 0"
        description="暂无收藏内容"
      >
        <template #image>
          <van-icon name="star-o" size="60" color="#dcdee0" />
        </template>
        <van-button
          round
          type="primary"
          size="small"
          to="/recipe/list"
          class="empty-btn"
        >
          去浏览食谱
        </van-button>
      </van-empty>

      <template v-else>
        <!-- 收藏列表 -->
        <div class="collection-list">
          <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
            <van-list
              v-model="loadingMore"
              :finished="finished"
              finished-text="没有更多了"
              @load="onLoad"
            >
              <div class="recipe-grid">
                <van-swipe-cell
                  v-for="item in collections"
                  :key="item.id"
                  :before-close="beforeClose"
                >
                  <div class="recipe-card" @click="goToRecipeDetail(item.id)">
                    <div class="card-image">
                      <img
                        :src="item.imageUrl || defaultImage"
                        :alt="item.name"
                      />
                      <div class="card-tag" v-if="item.difficulty">
                        {{ getDifficultyText(item.difficulty) }}
                      </div>
                    </div>
                    <div class="card-content">
                      <div class="card-title">{{ item.name }}</div>
                      <div class="card-meta">
                        <div class="rating">
                          <van-rate
                            v-model="item.rating"
                            readonly
                            size="12"
                            allow-half
                          />
                          <span>{{
                            item.rating ? item.rating.toFixed(1) : "暂无评分"
                          }}</span>
                        </div>
                        <div class="view-count">
                          <van-icon name="eye-o" />
                          <span>{{ formatNumber(item.viewCount || 0) }}</span>
                        </div>
                      </div>
                      <div class="collection-time">
                        收藏于: {{ formatDate(item.collectionTime) }}
                      </div>
                    </div>
                  </div>

                  <template #right>
                    <van-button
                      square
                      type="danger"
                      text="取消收藏"
                      class="delete-button"
                      @click="handleRemoveCollection(item.id)"
                    />
                  </template>
                </van-swipe-cell>
              </div>
            </van-list>
          </van-pull-refresh>
        </div>
      </template>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { useRouter } from "vue-router";
import { showToast, showConfirmDialog } from "vant";
import { useUserStore } from "@/stores/userStore";
import { getUserCollections, uncollectRecipe } from "@/api/recipe";
import defaultImage from "@/assets/default-recipe.jpg";

const router = useRouter();
const userStore = useUserStore();

// 状态变量
const collections = ref([]);
const loading = ref(true);
const refreshing = ref(false);
const loadingMore = ref(false);
const finished = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);

// 获取用户ID
const userId = computed(() => userStore.userId);

// 加载收藏列表
const loadCollections = async (refresh = false) => {
  if (!userId.value) return;

  if (refresh) {
    currentPage.value = 1;
    collections.value = [];
    finished.value = false;
  }

  try {
    const res = await getUserCollections(
      userId.value,
      currentPage.value,
      pageSize.value
    );

    if (res.code === 200 && res.data) {
      if (res.data.records && res.data.records.length > 0) {
        collections.value.push(...res.data.records);
        currentPage.value++;
        finished.value = collections.value.length >= res.data.total;
      } else {
        finished.value = true;
      }
    } else {
      showToast("获取收藏列表失败");
      finished.value = true;
    }
  } catch (error) {
    console.error("加载收藏列表失败", error);
    showToast("获取收藏列表失败");
    finished.value = true;
  } finally {
    loading.value = false;
    refreshing.value = false;
    loadingMore.value = false;
  }
};

// 刷新列表
const onRefresh = () => {
  loadCollections(true);
};

// 加载更多
const onLoad = () => {
  loadCollections();
};

// 格式化数字
const formatNumber = (num) => {
  if (num < 1000) return num;
  return (num / 1000).toFixed(1) + "k";
};

// 获取难度文本
const getDifficultyText = (difficulty) => {
  const map = {
    1: "简单",
    2: "普通",
    3: "困难",
  };
  return map[difficulty] || "普通";
};

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return "";
  const date = new Date(dateStr);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(
    2,
    "0"
  )}-${String(date.getDate()).padStart(2, "0")}`;
};

// 跳转到食谱详情
const goToRecipeDetail = (id) => {
  router.push(`/recipe/${id}`);
};

// 删除前确认
const beforeClose = ({ position, instance }) => {
  if (position === "right") {
    // 关闭滑动实例
    instance.close();
  }
};

// 取消收藏
const handleRemoveCollection = (recipeId) => {
  showConfirmDialog({
    title: "确认取消收藏",
    message: "确定要取消收藏吗？",
  }).then(async () => {
    try {
      const res = await uncollectRecipe(userId.value, recipeId);
      if (res.code === 200) {
        showToast("已取消收藏");
        // 更新列表
        collections.value = collections.value.filter(
          (item) => item.id !== recipeId
        );
      } else {
        showToast("操作失败");
      }
    } catch (error) {
      console.error("取消收藏失败", error);
      showToast("操作失败");
    }
  });
};

// 生命周期
onMounted(() => {
  loadCollections();
});
</script>

<style scoped>
.favorites-container {
  background-color: #f7f8fa;
  min-height: 100vh;
  padding-top: 46px;
}

.content {
  padding: 16px;
}

.empty-btn {
  margin-top: 16px;
}

.recipe-grid {
  display: grid;
  grid-template-columns: repeat(1, 1fr);
  gap: 16px;
}

.recipe-card {
  background-color: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.card-image {
  position: relative;
  height: 140px;
}

.card-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.card-tag {
  position: absolute;
  top: 8px;
  right: 8px;
  background-color: rgba(0, 0, 0, 0.6);
  color: #fff;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
}

.card-content {
  padding: 12px;
}

.card-title {
  font-weight: bold;
  font-size: 16px;
  margin-bottom: 8px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.card-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: #999;
  margin-bottom: 8px;
}

.rating {
  display: flex;
  align-items: center;
  gap: 4px;
}

.view-count {
  display: flex;
  align-items: center;
  gap: 2px;
}

.collection-time {
  font-size: 12px;
  color: #999;
}

.delete-button {
  height: 100%;
}

/* 响应式布局 */
@media (min-width: 768px) {
  .recipe-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (min-width: 992px) {
  .recipe-grid {
    grid-template-columns: repeat(3, 1fr);
  }
}
</style>
